<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Google Maps JavaScript API v3 Example: Directions Complex</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/standard.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style>
  body{
	text-align:center;
  }
  #map_canvas{
	margin: 20px auto;
	border: 1px dashed #C0C0C0;
	width: 800px;
	height: 500px;
  }
</style>

<script type="text/javascript">
  //将变量设置为全局变量方便方法调用
  var map;
	var directionDisplay;
  var directionsService;
	var rendererOptions = {
    draggable: true
  };

  function initialize() {
	 infowindow = new google.maps.InfoWindow(
    { 
      size: new google.maps.Size(150,50)
    });
		//注册一个路线服务
		directionsService = new google.maps.DirectionsService();
		//注册一个渲染路线的对象
		directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
		
    var latlng = new google.maps.LatLng(30.33508, 114.17211);
    var myOptions = {
      zoom: 10,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		//在地图上渲染路线
		directionsDisplay.setMap(map);
		//注册路线改变事件
		google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
      computeTotalDistance(directionsDisplay.directions);
    })
		var request = { 
					origin: "华中科技大学文华学院", 
					destination: "光谷软件园", 
					travelMode: google.maps.DirectionsTravelMode.DRIVING 
				}; 

		directionsService.route(request, RenderCustomDirections);
  }
	
	function RenderCustomDirections(response, status) {
		if(status == google.maps.DirectionsStatus.OK) {
				directionsDisplay.setDirections(response);
			}
	}

	function computeTotalDistance(result) {
    var total = 0;
    var myroute = result.routes[0];
    for (i = 0; i < myroute.legs.length; i++) {
      total += myroute.legs[i].distance.value;
    }
    total = total / 1000.
    document.getElementById("distance").innerHTML = "Total Distance: "+ total + " km";
  }  
</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
	<div id="distance" style="position: relative;right:10px;top:10px;height 100%"></div>
</body>
</html>